﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class CheckoutEquipListControl : RSBaseUserControl
    {
        private int _companyid = 0;
        private int _workorderid = 0;

        
        protected void Page_Load(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            _companyid = userIdentity.RSCompanyId;
            if (!String.IsNullOrEmpty(Request.QueryString["workorderid"]))
                _workorderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());

        }
        protected void gvEquipmentList_RowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int selectedid = Convert.ToInt32(gvEquipmentList.DataKeys[e.RowIndex].Value);
                RemoveSelectedItemFromList(selectedid);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        private void RemoveSelectedItemFromList(int selectedid)
        {
            List<CheckoutEquip> selParts = new List<CheckoutEquip>();
            if (Session["CHECKOUT_EQUIP"] != null)
                selParts = (List<CheckoutEquip>)Session["CHECKOUT_EQUIP"];

            if (selParts.Count > 0)
            {
                for (int i = 0; i < selParts.Count; i++)
                {
                    if (selParts[i].ProductId == selectedid)
                    {
                        selParts.RemoveAt(i);
                        break;
                    }
                }
            }

            Session["CHECKOUT_EQUIP"] = selParts;
            gvEquipmentList.DataSource = selParts;
            gvEquipmentList.DataBind();

            if (gvEquipmentList.Rows.Count > 0)
                pnlEquipmentList.Visible = true;
            else
                pnlEquipmentList.Visible = false;
        }
        public void ShowEquipmentList(int companyid)
        {
            LoadEquipmentList(companyid);
        }

        protected void btnSubmit_Click(Object sender, EventArgs e)
        {
            List<CheckoutEquip> selParts = new List<CheckoutEquip>();
            if (Session["CHECKOUT_EQUIP"] != null)
                selParts = (List<CheckoutEquip>)Session["CHECKOUT_EQUIP"];

            int productid = 0;
            int quantity = 0;
            if (selParts.Count > 0)
            {
                for (int i = 0; i < selParts.Count; i++)
                {
                    productid = Convert.ToInt32(selParts[i].ProductId);
                    quantity = Convert.ToInt32(selParts[i].Quantity);
                    if (_companyid > 0 && _workorderid > 0 && productid > 0 && quantity > 0)
                    {
                        SaveSelectedPartToWorkOrder(_companyid, _workorderid, productid, quantity);
                    }
                }
                //string prevurl = Session["PreviousURL"].ToString();
                string prevurl = string.Empty;
                if (Session["PreviousURL"] != null)
                    prevurl = Session["PreviousURL"].ToString();
                else
                    prevurl = Request.UrlReferrer.ToString();

                if(!prevurl.Contains("tabindex="))
                    prevurl = prevurl + "&tabindex=3";
                ucModalActionMessageControl.ShowModal("Equipment Added Successfully!", prevurl, true);
            }
            Session["CHECKOUT_EQUIP"] = null;
        }
        protected void btnReturn_Click(Object sender, EventArgs e)
        {
            int WorkOrderid = 0;
            if(Request.QueryString["workorderid"] != null)
                WorkOrderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
            Response.Redirect("~/RS/SBM/RSWorkOrderEquips.aspx?workorderid=" + WorkOrderid);
        }
        private void SaveSelectedPartToWorkOrder(int companyid, int WorkOrderid, int productid, int quantity)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@quantity", SqlDbType.Int, 0, ParameterDirection.Input, quantity);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "INSERT INTO rs_tblWorkOrderEquip (WorkOrderid, productid, quantity, companyid, unitprice) VALUES(@WorkOrderid, @productid, @quantity, @companyid, (select i.unitprice from rs_tblInventory i where i.productid=@productid and i.companyid=@companyid))");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);

        }

        public void LoadEquipmentList(int companyid)
        {
            if (Session["CHECKOUT_EQUIP"] != null)
            {
                List<CheckoutEquip> selParts = new List<CheckoutEquip>();
                selParts = (List<CheckoutEquip>)Session["CHECKOUT_EQUIP"];

                if (selParts.Count > 0)
                {
                    String strSQL = "SELECT c.ProductId,c.ProductName,c.QuantityPerUnit,c.UnitPrice,c.UnitsInStock,c.UnitsOnOrder, '0' AS Quanity, c.ProductDesc," +
                                        "c.Discontinued,c.ModelNo,c.ProductCode,c.ParentId, (SELECT p.ProductName FROM rs_tblInventory p WHERE p.ProductId=c.ParentId) as CategoryName,c.SupplierID,c.CompanyId " +
                                        " FROM rs_tblInventory c WHERE c.IsEquipment=1 AND c.companyid=@companyid AND c.ParentId > 0  order by CategoryName ";
                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);
                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        while (myDataReader.Read())
                        {
                            if (selParts.Count > 0)
                            {
                                for (int i = 0; i < selParts.Count; i++)
                                {
                                    if (selParts[i].ProductId == int.Parse(myDataReader["ProductId"].ToString()))
                                    {
                                        selParts[i].ProductName = myDataReader["ProductName"].ToString();
                                        selParts[i].UnitPrice = Convert.ToDecimal(myDataReader["UnitPrice"].ToString());
                                        selParts[i].ParentId = int.Parse(myDataReader["ParentId"].ToString());
                                        selParts[i].ModelNo = myDataReader["ModelNo"].ToString();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    gvEquipmentList.DataSource = selParts;
                    gvEquipmentList.DataBind();
                    myConnection.Close();
                    pnlEquipmentList.Visible = true;
                }
                else
                {
                    pnlEquipmentList.Visible = false;
                }
            }
        }
    }
}